package com.dahua.ui.user;

import android.app.Activity;
import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.view.ViewCompat;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ScrollView;
import android.widget.TextView;
import android.widget.Toast;


import com.dahua.R;
import com.dahua.bean.User;
import com.dahua.ui.SplashActivity;
import com.dahua.ui.base.BaseActivity;
import com.dahua.ui.main.MainAct;
import com.dahua.utils.HttpUtils;
import com.dahua.utils.IMMListenerRelativeLayout;
import com.dahua.utils.InputWindowListener;
import com.dahua.utils.UserPreference;

import org.apache.http.params.HttpParams;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.Properties;
import java.util.Set;


import static android.content.ContentValues.TAG;


public class LoginAct extends BaseActivity implements View.OnClickListener {
    EditText etName, etPwd;
    TextView text_notice, text_sign_in, text_register, tv_lang;
    LinearLayout lyLogin;
    ImageView iv_back, iv_logo;
    IMMListenerRelativeLayout mainlayout;

    public Dialog loadingDialog;


    //    ScrollView sv_content;
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.welcome);
        initView();
    }

    private void initView() {

//        Window window = getWindow();
//        //设置透明状态栏,这样才能让 ContentView 向上
//        window.addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
//        //需要设置这个 flag 才能调用 setStatusBarColor 来设置状态栏颜色
//        window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
//        //设置状态栏颜色
////        window.setStatusBarColor(statusColor);
//        ViewGroup mContentView = (ViewGroup) findViewById(Window.ID_ANDROID_CONTENT);
//        View mChildView = mContentView.getChildAt(0);
//        if (mChildView != null) {
//            //注意不是设置 ContentView 的 FitsSystemWindows, 而是设置 ContentView 的第一个子 View . 使其不为系统 View 预留空间.
//            ViewCompat.setFitsSystemWindows(mChildView, false);
//        }
        text_sign_in = findViewById(R.id.text_sign_in);
        text_register = findViewById(R.id.text_register);
        text_notice = findViewById(R.id.text_notice);
        tv_lang = findViewById(R.id.tv_lang);

        etName = (EditText) findViewById(R.id.et_name);
        etPwd = (EditText) findViewById(R.id.et_pwd);
        lyLogin = (LinearLayout) findViewById(R.id.ly_login);
        if (UserPreference.getInstance(getApplicationContext()).getLogonId() != null) {
            etName.setText(UserPreference.getInstance(getApplicationContext()).getLogonId());
        }
        iv_back = (ImageView) findViewById(R.id.iv_back);
        iv_logo = (ImageView) findViewById(R.id.iv_logo);
        iv_back.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
        tv_lang.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent i = new Intent(getApplicationContext(), RegisterAct.class);
                i.putExtra("url", "views/language/switching.html");
                startActivity(i);
            }
        });

//        sv_content = (ScrollView) findViewById(R.id.sv_content);

        mainlayout = (IMMListenerRelativeLayout) findViewById(R.id.mainlayout);
        mainlayout.setListener(new InputWindowListener() {
            @Override
            public void show() {
//                sv_content.smoothScrollTo(0, dipToPx(LoginAct.this, 100));
                iv_logo.setVisibility(View.GONE);
            }

            @Override
            public void hidden() {
//                sv_content.smoothScrollTo(0, 0);
                iv_logo.setVisibility(View.VISIBLE);
            }
        });
    }


    @Override
    protected void onResume() {
        super.onResume();

        String lang = UserPreference.getInstance(this).getLang();
        if (lang.equals("null")) {
            lang = "en";
        }
        readAssetsFile(lang);
    }

    private Properties properties;

    private void readAssetsFile(String lang) {
        properties = new Properties();
        try {
            InputStream is = getAssets().open("part2/resources/js/lang/lang_" + lang + ".properties");
            BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(is));
            properties.load(bufferedReader);
        } catch (Exception e) {
            e.printStackTrace();
        }
        etName.setHint(properties.getProperty("User_Center_Company_e-mail_address"));
        etPwd.setHint(properties.getProperty("User_Center_Password"));
        text_sign_in.setText(properties.getProperty("User_Center_Sign_in"));
        text_register.setText(properties.getProperty("User_Center_Registration"));
        tv_lang.setText(properties.getProperty("language_msg"));
        text_notice.setText(properties.getProperty("User_Center_Forgot_your_password"));
    }

    public int dipToPx(Context context, float dipValue) {
        final float scale = context.getResources().getDisplayMetrics().density;
        return (int) (dipValue * scale + 0.5f);
    }

    String pwd;

    public void login(View view) {
        String name = etName.getText().toString();
        pwd = etPwd.getText().toString();
        if (name == null || name.isEmpty()) {
            showToast(properties.getProperty("User_name_cannot_be_empty"));
            return;
        }
        if (pwd == null || pwd.isEmpty()) {
            showToast(properties.getProperty("Password_cannot_be_empty"));
            return;
        }
        lyLogin.setEnabled(false);
        showLoadingDialog();
        HttpUtils.getInstance().login(handler, name, pwd);
    }

    private static final int MSG_SET_ALIAS = 1001;
    private Handler handler = new Handler() {

        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case 1:
//                    JPushInterface.resumePush(getApplicationContext());
                    User user = new User();
                    JSONObject jo0 = (JSONObject) msg.obj;
                    JSONObject jo1 = jo0.optJSONObject("object");
                    user.setUid(jo1.optString("id"));
                    user.setCountryId(jo1.optString("countryId"));
                    user.setLogonId(jo1.optString("logonId"));
                    user.setName(jo1.optString("name"));
                    user.setStatus(jo1.optString("status"));
                    JSONObject jo2 = null;
                    try {
                        jo2 = jo1.getJSONObject("role");
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                    user.setRole(jo2.optString("id"));
                    UserPreference.getInstance(getApplicationContext()).setUid(user.getUid());
                    UserPreference.getInstance(getApplicationContext()).setName(user.getName());
                    UserPreference.getInstance(getApplicationContext()).setCountryId(user.getCountryId());
                    UserPreference.getInstance(getApplicationContext()).setRole(user.getRole());
                    UserPreference.getInstance(getApplicationContext()).setLogonId(user.getLogonId());
                    UserPreference.getInstance(getApplicationContext()).setStatus(user.getStatus());
                    UserPreference.getInstance(getApplicationContext()).setPwd(pwd);
                    //调用JPush API设置Alias
                    mHandler.sendMessage(mHandler.obtainMessage(MSG_SET_ALIAS, user.getCountryId()));
                    hideLoadingDialog();
                    showToast(properties.getProperty("login_success"));
                    lyLogin.setEnabled(true);
                    UserPreference.getInstance(getApplicationContext()).setLogin(true);
//                    startActivity(new Intent(getApplicationContext(), MainAct.class));
                    finish();
                    break;
                case 2:
                    hideLoadingDialog();
                    showToast(msg.obj.toString());
                    lyLogin.setEnabled(true);
                    break;
            }
        }

        ;
    };
    private final Handler mHandler = new Handler() {
        @Override
        public void handleMessage(android.os.Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case MSG_SET_ALIAS:
                    break;
            }
        }
    };

    public void register(View view) {
        Intent i = new Intent(getApplicationContext(), RegisterAct.class);
        i.putExtra("url", "views/user/register.html");
        startActivity(i);
    }

    public void forget(View view) {
        Intent i = new Intent(getApplicationContext(), RegisterAct.class);
        i.putExtra("url", "views/user/forgetPwd.html");
        startActivity(i);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
        }
    }

}
